const fs = require('fs');
const moment = require('moment');
const superagent = require('superagent');
const inquirer = require('inquirer');
const chalk = require('chalk');
const { kebabCase } = require('lodash');
const log = console.log;
const categories = ['编程笔记', '历史人文', '读书笔记'];

function getSlug(name) {
  name = encodeURIComponent(name);
  return new Promise((resolve) => {
    superagent
      .get(
        `http://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i=${name}`
      )
      .then((resp) => {
        const body = resp.body.translateResult;
        let text = '';
        body.forEach((t) => {
          t.forEach((tt) => {
            text = tt.tgt;
          });
        });
        resolve(text);
      });
  });
}

module.exports = function () {
  inquirer
    .prompt([
      {
        type: 'input',
        name: 'title',
        message: '请输入文章标题:',
        validate: (input, answers) => {
          if (input) {
            return true;
          }
          return '👀必须提供文章标题!';
        },
      },
      {
        type: 'input',
        name: 'tags',
        message: '请输入文章标签(多个标签使用空格分隔):',
        validate(input, answers) {
          if (input) {
            return true;
          }
          return `👀必须提供文章标签!`;
        },
      },
      {
        type: 'list',
        name: 'category',
        message: '请选择文章分类:',
        choices: [...categories],
        default: categories[0],
      },
    ])
    .then((answers) => {
      let { tags } = answers;
      let date = moment().format('YYYY-MM-DD HH:mm:ss');
      tags = tags
        .split(' ')
        .filter((t) => t && t.trim())
        .map((t) => `'${t}'`);

      answers.tags = tags;
      answers.date = date;
      getSlug(answers.title).then((slug) => {
        slug = kebabCase(slug);
        const template = `---
title: ${answers['title']}
date: ${date}
category:
  - ${answers.category}
tags: [${tags.join(',')}]
slug: ${slug}
thumbnail: ''
---  
    `;
        fs.writeFileSync(`${answers['title']}.md`, template);
        log(`新建文章: ${chalk.green(`${answers['title']}.md`)} 完成!👏`);
      });
    });
};
